package org.jeecg.modules.xxgx.spgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.common.util.LoginUserUtil;
import org.jeecg.modules.innerApi.bwgfApi.service.IBaiWangSkfpService;
import org.jeecg.modules.innerApi.common.responseDto.ZnfmRtn;
import org.jeecg.modules.xxgx.common.service.IXxBase;
import org.jeecg.modules.xxgx.spgl.entity.CsXxProduct;
import org.jeecg.modules.xxgx.spgl.service.ICsXxProductService;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductEditSlvBatchParam;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductPlfmParam;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductPlznfmParam;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductZnfmBatchVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 商品
 * @Author: jeecg-boot
 * @Date:   2023-08-21
 * @Version: V1.0
 */
@Api(tags="商品")
@RestController
@RequestMapping("/xxgx/spgl/csXxProduct")
@Slf4j
public class CsXxProductController extends JeecgController<CsXxProduct, ICsXxProductService> {
	@Autowired
	private ICsXxProductService csXxProductService;
	 @Autowired
	 IBaiWangSkfpService baiWangSkfpService;
	 @Autowired
	 IXxBase xxBase;
	
	/**
	 * 分页列表查询
	 *
	 * @param csXxProduct
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "商品-分页列表查询")
	@ApiOperation(value="商品-分页列表查询", notes="商品-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CsXxProduct>> queryPageList(CsXxProduct csXxProduct,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String companyId = LoginUserUtil.getQyxxByLoginUser().getId();
		QueryWrapper<CsXxProduct> queryWrapper = QueryGenerator.initQueryWrapper(csXxProduct, req.getParameterMap());

		//处理共享标志（查询本公司商品或者非本公司但共享的商品）
		// and (company_id = ? or (company_id != ? and gxbz = ?))
		queryWrapper.and(wrapper -> wrapper.eq("company_id", companyId)
				.or(wrapper1 -> wrapper1.ne("company_id", companyId).eq("gxbz", "1"))
		);
		Page<CsXxProduct> page = new Page<CsXxProduct>(pageNo, pageSize);
		IPage<CsXxProduct> pageList = csXxProductService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param csXxProduct
	 * @return
	 */
	@AutoLog(value = "商品-添加")
	@ApiOperation(value="商品-添加", notes="商品-添加")
	@RequiresPermissions("xxgx.spgl:cs_xx_product:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CsXxProduct csXxProduct) {
		String companyId = LoginUserUtil.getQyxxByLoginUser().getId();
		csXxProduct.setCompanyId(companyId);
		csXxProductService.save(csXxProduct);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param csXxProduct
	 * @return
	 */
	@AutoLog(value = "商品-编辑")
	@ApiOperation(value="商品-编辑", notes="商品-编辑")
	@RequiresPermissions("xxgx.spgl:cs_xx_product:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CsXxProduct csXxProduct) {
		csXxProductService.updateById(csXxProduct);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品-通过id删除")
	@ApiOperation(value="商品-通过id删除", notes="商品-通过id删除")
	@RequiresPermissions("xxgx.spgl:cs_xx_product:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		csXxProductService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商品-批量删除")
	@ApiOperation(value="商品-批量删除", notes="商品-批量删除")
	@RequiresPermissions("xxgx.spgl:cs_xx_product:deleteBatch")
	@PostMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(
			@ApiParam(value = "商品ID数组", required = true)
			@RequestBody List<String> ids) {
		this.csXxProductService.removeByIds(Arrays.asList(ids.toArray()));
		return Result.OK("批量删除成功!");
	}
	 @AutoLog(value = "商品-全部删除")
	 @ApiOperation(value="商品-全部删除", notes="商品-全部删除")
	 @RequiresPermissions("xxgx.spgl:cs_xx_product:deleteAll")
	 @DeleteMapping(value = "/deleteAll")
	 public Result<String> deleteAll() {
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 LambdaQueryWrapper<CsXxProduct> queryWrapper = new LambdaQueryWrapper<>();
		 queryWrapper.eq(CsXxProduct::getTenantId,user.getLoginTenantId())
						 .eq(CsXxProduct::getCompanyId,user.getCompanyId());
		 csXxProductService.remove(queryWrapper);

		 return Result.OK("全部删除成功!");
	 }

	 @AutoLog(value = "商品-批量修改税率")
	 @ApiOperation(value="商品-批量修改税率", notes="商品-批量修改税率")
	 @RequiresPermissions("xxgx.spgl:cs_xx_product:editSlvBatch")
	 @RequestMapping(value = "/editSlvBatch", method = {RequestMethod.POST})
	 public Result<String> editSlvBatch(@RequestBody CsXxProductEditSlvBatchParam csXxProductEditSlvBatchVO) {
		 csXxProductService.updateProductSlvBatch(csXxProductEditSlvBatchVO);
		 return Result.OK("修改成功!");
	 }

	 @AutoLog(value = "商品-批量赋码")
	 @ApiOperation(value="商品-批量赋码", notes="商品-批量赋码")
	 @RequiresPermissions("xxgx.spgl:cs_xx_product:editPlfm")
	 @RequestMapping(value = "/editPlfm", method = {RequestMethod.POST})
	 public Result<String> editPlfm(@RequestBody CsXxProductPlfmParam csXxProductPlfmParam) {
		 csXxProductService.updateProductPlfmBatch(csXxProductPlfmParam);
		 return Result.OK("修改成功!");
	 }

	 @AutoLog(value = "商品-批量智能赋码保存")
	 @ApiOperation(value="商品-批量智能赋码保存", notes="商品-批量智能赋码保存")
	 @RequiresPermissions("xxgx.spgl:cs_xx_product:editPlznfm")
	 @RequestMapping(value = "/editPlznfm", method = {RequestMethod.POST})
	 public Result<String> editPlznfm(@RequestBody List<CsXxProductPlznfmParam> csXxProductPlznfmParamList) {
		 csXxProductService.updateProductPlznfmBatch(csXxProductPlznfmParamList);
		 return Result.OK("修改成功!");
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "商品-通过id查询")
	@ApiOperation(value="商品-通过id查询", notes="商品-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CsXxProduct> queryById(@RequestParam(name="id",required=true) String id) {
		CsXxProduct csXxProduct = csXxProductService.getById(id);
		if(csXxProduct==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(csXxProduct);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param csXxProduct
    */
	@ApiOperation(value="商品-导出excel", notes="商品-导出excel")
    @RequiresPermissions("xxgx.spgl:cs_xx_product:exportXls")
    @RequestMapping(value = "/exportXls", method = RequestMethod.POST)
    public ModelAndView exportXls(HttpServletRequest request, CsXxProduct csXxProduct) {
        return super.exportXls(request, csXxProduct, CsXxProduct.class, "商品");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	@ApiOperation(value="商品-通过excel导入数据", notes="商品-通过excel导入数据")
    @RequiresPermissions("xxgx.spgl:cs_xx_product:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		String sffg = request.getParameter("sffg");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(1);
			params.setHeadRows(1);
			params.setNeedSave(true);

			try {
				List<CsXxProduct> list = ExcelImportUtil.importExcel(file.getInputStream(), CsXxProduct.class, params);
				return csXxProductService.uploadProduct(list,sffg);
			}catch (Exception e){
				log.error(e.getMessage(),e);
				return Result.error(e.getMessage());
			}
		}

		return Result.OK("导入成功");
    }

	 @AutoLog(value = "商品-批量智能赋码")
	 @ApiOperation(value="商品-批量智能赋码", notes="商品-批量智能赋码")
	 @PostMapping(value = "/znfmBatch")
	 public Result<List<CsXxProductZnfmBatchVo>> znfmBatch(
			 @ApiParam(value = "商品ID数组", required = true)
			 @RequestBody List<String> ids) {
		 List<CsXxProductZnfmBatchVo> rtnList = new ArrayList<>();

		 List<ZnfmRtn> znfmList = null;
		 for(String id : ids) {
			 CsXxProduct csXxProduct = csXxProductService.getById(id);
			 String spmc = csXxProduct.getSpmc();
			 CsXxProductZnfmBatchVo znfmBatchVo = new CsXxProductZnfmBatchVo();
			 znfmBatchVo.setSpid(csXxProduct.getId());
			 znfmBatchVo.setSpmc(spmc);
			 znfmList = xxBase.znfm(spmc).getResult();
			 znfmBatchVo.setFmjg(znfmList);

			 if(znfmList!=null){
				 rtnList.add(znfmBatchVo);
			 }
		 }
		 return Result.OK("智能赋码成功",rtnList);
	 }

}
